package com.chuji.crmcj.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.text.format.DateUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;

import com.alibaba.fastjson.JSON;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.chuji.crmcj.R;
import com.chuji.crmcj.act.OrderDetialAct;
import com.chuji.crmcj.adapter.OrdDelAdp;
import com.chuji.crmcj.adapter.OrderAdapter;
import com.chuji.crmcj.bean.OrdDelInfo;
import com.chuji.crmcj.bean.OrderListInfo;
import com.chuji.crmcj.bean.SureLoseReadInfo;
import com.chuji.crmcj.utils.ConstantValue;
import com.chuji.crmcj.utils.SPUtils;
import com.chuji.crmcj.utils.UIUtils;
import com.chuji.crmcj.utils.UrlUtils;
import com.chuji.crmcj.utils.VolleyUtil;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;

import java.util.List;

/**
 * Created by w.pitt on 2016/1/28.
 */
public class OrderFragment extends BaseFragment implements AdapterView.OnItemClickListener {

    private PullToRefreshListView mLvOrder;
    private OrdDelAdp ordDelAdp;
    private int roleType;
    private OrderListInfo orderListInfo;
    private OrderAdapter orderAdapter;
    private OrdDelInfo ordDelInfo;
    private String userID;
    private List<OrderListInfo.ApiParamObjEntity> mOrderList;
    /*确认已读*/
    private SureLoseReadInfo sureLoseReadInfo;
    @Override
    public View initView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = View.inflate(UIUtils.getContext(), R.layout.fragment_order, null);
        mLvOrder = (PullToRefreshListView) view.findViewById(R.id.lv_order);

        mLvOrder.getRefreshableView().setDivider(null);
        mLvOrder.getRefreshableView().setSelector(android.R.color.transparent);
        return view;
    }

    @Override
    public void initData() {
        customerID = SPUtils.getString(UIUtils.getContext(), "CustomerID", "");
        roleType = SPUtils.getInt(UIUtils.getContext(), "RoleType", -1);
        userID = SPUtils.getString(UIUtils.getContext(), "UserID", "");

        if (roleType == 1) {
            mLvOrder.setMode(PullToRefreshBase.Mode.PULL_FROM_END);
        }
    }

    @Override
    public void onStart() {
        super.onStart();
        if (roleType == 1) {
            /*销售端*/
            reqOrderList(1);
        } else {
            /*Todo 请求经理端的  订单跟进中*/
            reqFolOrder();
        }
    }

    private void reqFolOrder() {
        String strURL = String.format(UrlUtils.OrderDealPeter + "&UserID=%s&Type=0", userID);
        volleyRequest(strURL, new Response.Listener<String>() {
            @Override
            public void onResponse(String s) {
                ordDelInfo = JSON.parseObject(s, OrdDelInfo.class);
                UIUtils.runInMainThread(new Runnable() {
                    @Override
                    public void run() {
                        if (ordDelInfo.getCount() != 0) {
                            if (ordDelAdp == null) {
                                ordDelAdp = new OrdDelAdp(UIUtils.getContext(), ordDelInfo);
                                mLvOrder.setAdapter(ordDelAdp);
                            } else {
                                ordDelAdp.notifyDataSetChanged();
                            }
                        }
                    }
                });
            }
        });
    }

    private void reqOrderList(int pageIndex) {
        String strURL = String.format(UrlUtils.GETORDERINFO + "&SalesID=%s&PageSize=10&PageIndex=%d", userID, pageIndex);
        volleyRequest(strURL, new Response.Listener<String>() {
                    @Override
                    public void onResponse(String s) {
                        orderListInfo = JSON.parseObject(s, OrderListInfo.class);
                        UIUtils.runInMainThread(new Runnable() {
                                                    @Override
                                                    public void run() {
                                                        if (orderListInfo.getApiParamObj().size() != 0) {
                                                            if (orderAdapter == null) {
                                                                mOrderList = orderListInfo.getApiParamObj();
                                                                orderAdapter = new OrderAdapter(UIUtils.getContext(), mOrderList);
                                                                mLvOrder.setAdapter(orderAdapter);
                                                            } else {
                                                                mOrderList = orderAdapter.getList();
                                                                //分页加载
                                                                if (orderListInfo.getApiParamObj().size() == 0) {
                                                                    UIUtils.showToastSafe("已经到达底部");
                                                                } else {
                                                                    //滚动加载数据
                                                                    mOrderList.addAll(orderListInfo.getApiParamObj());
                                                                }
                                                                orderAdapter.notifyDataSetChanged();
                                                            }
                                                            isRefreshing = false;
                                                            mLvOrder.onRefreshComplete();
                                                        }
                                                    }
                                                }

                        );
                    }
                }

        );
    }

    private boolean isRefreshing;

    @Override
    public void initListener() {
        super.initListener();
        mLvOrder.setOnItemClickListener(this);

        mLvOrder.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ListView>() {
            //下拉刷新
            @Override
            public void onPullDownToRefresh(
                    PullToRefreshBase<ListView> refreshView) {
                mLvOrder.onRefreshComplete();
            }

            //上拉加载
            @Override
            public void onPullUpToRefresh(
                    PullToRefreshBase<ListView> refreshView) {
                String str = DateUtils.formatDateTime(UIUtils.getContext(), System.currentTimeMillis(), DateUtils.FORMAT_SHOW_TIME | DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_ABBREV_ALL);
                mLvOrder.getLoadingLayoutProxy().setRefreshingLabel("正在加载");
                mLvOrder.getLoadingLayoutProxy().setPullLabel("上拉加载更多");
                mLvOrder.getLoadingLayoutProxy().setReleaseLabel("释放开始加载");
                refreshView.getLoadingLayoutProxy().setLastUpdatedLabel("最后加载时间:" + str);
                if (!isRefreshing) {
                    isRefreshing = true;
                    getBoutiqueNetData();
                } else {
                    mLvOrder.onRefreshComplete();
                }
            }
        });
    }

    private int initIndex = 1;

    //上拉加载专用
    private void getBoutiqueNetData() {
//        //第一次
//        if (searchList == null) {
//            searchList = new ArrayList<SearchPotenInfo.ApiParamObjEntity>();
//            initIndex = 1;
//        } else {
        initIndex++;
//        }
        reqOrderList(initIndex);
    }


    private String customerID;
    private String tel;
    private String carModel;
    private String name;
    private String orderInfoID;

    @Override
    public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
        Intent intent = new Intent(UIUtils.getContext(), OrderDetialAct.class);
        intent.putExtra("Lable", ConstantValue.OrderFragment);
        if (roleType == 1) {
            customerID = orderListInfo.getApiParamObj().get(i - 1).getCustomerID();
            tel = orderListInfo.getApiParamObj().get(i - 1).getTel();
            orderInfoID = orderListInfo.getApiParamObj().get(i - 1).getOrderInfoID();
            carModel = orderListInfo.getApiParamObj().get(i - 1).getCarModel();
            name = orderListInfo.getApiParamObj().get(i - 1).getName();
        } else {
            orderInfoID = ordDelInfo.getApiParamObj().get(i - 1).getOrderInfoID();
            tel = ordDelInfo.getApiParamObj().get(i - 1).getCustormerTel();
            carModel = ordDelInfo.getApiParamObj().get(i - 1).getCarModel();
            name = ordDelInfo.getApiParamObj().get(i - 1).getCustomerName();
        }
        if(ordDelInfo.getApiParamObj().get(0).getIsRead()==0){
            SureRead(userID,"跟进中",ordDelInfo.getApiParamObj().get(0).getOrderInfoID());
        }
        intent.putExtra("OrderInfoID", orderInfoID);
        intent.putExtra("CustomerID", customerID);
        intent.putExtra("Tel", tel);
        intent.putExtra("CarModel", carModel);
        intent.putExtra("Name", name);
        startActivity(intent);
    }
    //获取读取信息
    public void SureRead(String UserID,String Remark,String BusinessId){
        String strURL = String.format(UrlUtils.SUBMIT_Lose_ISREAD+"&UserID="+UserID+"&Remark="+Remark+"&BusinessId="+BusinessId);
        StringRequest stringRequest = new StringRequest(Request.Method.GET, strURL, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                sureLoseReadInfo = JSON.parseObject(response,SureLoseReadInfo.class);
                if(sureLoseReadInfo.getApiParamObj().get(0).getIsok().equals("0")){
                    UIUtils.showToastSafe("消息已读");
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                error.printStackTrace();
                System.out.println("失败" + error);
                UIUtils.showToastSafe("请检查网络");
            }
        });
        // Add the request to the RequestQueue.
        VolleyUtil.getRequestQueue().add(stringRequest);
    }
}
